//
//  XYCRouteMatcher.m
//  WLRRoute_Example
//
//  Created by xyc on 2018/2/6.
//  Copyright © 2018年 Neo. All rights reserved.
//

#import "XYCRouteMatcher.h"
#import "XYCRegularExpression.h"
#import "XYCRouteRequest.h"
#import "XYCMatchResult.h"

@interface XYCRouteMatcher()

@property(nonatomic,copy) NSString * scheme;
@property(nonatomic,strong)XYCRegularExpression * regexMatcher;

@end

@implementation XYCRouteMatcher

+(instancetype)matcherWithRouteExpression:(NSString *)expression{
    return [[self alloc]initWithRouteExpression:expression];
}
-(instancetype)initWithRouteExpression:(NSString *)routeExpression{
    
    if (![routeExpression length]) {
        return nil;
    }
    if (self = [super init]) {
        /*
         将路由的url匹配表达式进行分割，分割出scheme和后续部分,后续部分形成WLRRegularExpression对象，并将url匹配表达式保存在_originalRouteExpression变量中
         */
        //routeExpression   /signin/:phone([0-9]+)    /userDetail  等
        NSArray * parts = [routeExpression componentsSeparatedByString:@"://"];
        _scheme = parts.count>1?[parts firstObject]:nil;
        _routeExpressionPattern =[parts lastObject];//_routeExpressionPattern   /signin/:phone([0-9]+)    /userDetail  等
        _regexMatcher = [XYCRegularExpression expressionWithPattern:_routeExpressionPattern];//解析出url的正则表达式
        _originalRouteExpression = routeExpression;
        
    }
    return self;
    
}

-(XYCRouteRequest *)createRequestWithURL:(NSURL *)URL primitiveParameters:(NSDictionary *)primitiveParameters{
    
    NSString * urlString = [NSString stringWithFormat:@"%@%@",URL.host,URL.path];
    //匹配schema，不匹配的就返回nil。如果注册的时候没有schema，那就不判断
    if (self.scheme.length && ![self.scheme isEqualToString:URL.scheme]) {
        return nil;
    }
    //匹配urlstring和之前计算出来的正则表达式，没有匹配到的话就直接返回nil
    XYCMatchResult * result = [self.regexMatcher matchResultForString:urlString];
    if (!result.isMatch) {
        return nil;
    }
    XYCRouteRequest * request = [[XYCRouteRequest alloc]initWithURL:URL routeExpression:self.routeExpressionPattern routeParameters:result.paramProperties primitiveParameters:primitiveParameters];
    return request;
    
}

@end
